import { PERMISSION_LIST } from '@/Utils/CONST'
import routerList from '@/Utils/router.config'

const routerConfig = formatRouterConfig(routerList)

export const checkPermission = (key, method) => {
  const router = routerConfig[key]
  if (!router) {
    return false
  }
  const permissionList = JSON.parse(localStorage.getItem(PERMISSION_LIST) || '[]')
  const permission = permissionList.find(v => {
    const flag = v.resource_url === router.resourceUrl
    return method ? flag && v.method.toLowerCase() === method.toLowerCase()
      : flag
  })
  return !!permission
}

function formatRouterConfig(routerList, obj = {}) {
  routerList.forEach(item => {
    obj[item.key] = {
      name: item.name,
      resourceUrl: item.resourceUrl,
      key: item.key,
      method: item.method,
      type: item.type,
    }
    if (item.children && item.children.length) {
      formatRouterConfig(item.children, obj)
    }
  })
  return obj
}
